<?php

/**
 * Description of deals_controller
 * @property Deal $Deal Description
 */
class DealsController extends DealsAppController {

	var $name = 'Deals';
	var $helpers = array('Html', 'Form', 'Cms.Index');
	var $components = array('Auth','Session','RequestHandler','Email');
	protected $autoAdminActions = array('admin_bulkDelete','admin_bulkPublish','admin_bulkUnpublish');

	function beforeFilter()
	{
		$this->Auth->allow('index','view','newsletter');
		$this->Auth->loginAction = array("plugin"=>"users","controller"=>"users",'action'=>'login');
		parent::beforeFilter();
		$this->__checkDealsFunctionality();
	}

	function admin_add($listingId = null)
	{
		//echo "sdfsdf"; exit;
		$redirectUrl = array("plugin"=>"backend","controller"=>"backend","action"=>"index");
		//$this->__checkDealsFunctionality($redirectUrl);
		$listing = $this->Deal->Listing->find("first",array("conditions"=>array("Listing.id"=>$listingId),"recursive"=>-1));
		//prd($listing);
		if(!$listingId || empty($listing))
		{
			$this->errorMsg(__('Invalid Listing', true));
			$this->redirect($redirectUrl);
		}

		if(AppUtility::allowPaidListing())
		{
			if(!$this->Deal->isDealEnabledInPaidListing($listingId))
			{
				$this->errorMsg(__("Deal status cannot be added due to listing's plan restriction."));
				$this->redirect($redirectUrl);
				return;
			} else if($this->Deal->isActiveDealsLimitReached($listingId)) {
				$this->errorMsg(__("Active deal limit exhausted"));
				$this->redirect(array("plugin"=>"deals","controller"=>"deals",'action'=>'index',$listingId));
				return;
			}
		}
		if (!empty($this->data))
		{
			$this->data['Deal']['listing_id'] = $listingId;
			$this->Deal->create();
			if($this->Deal->saveAll($this->data)) //$this->_save($this->data)
			{
				$this->SuccessMsg(__('The deal has been saved', true));
				$this->redirect(array("plugin"=>"deals","controller"=>"deals",'action'=>'index',$listingId));
			} else {
				$this->errorMsg(__('The deal could not be saved. Please, try again.', true));
			}
		}
		$this->Deal->setDealCategoryOptions();
	
		$pageTitle = sprintf(__("Add new deal for listing : %s"),$listing['Listing']['title']);
		$this->pageTitle = $pageTitle;
		$this->set(compact('listing', 'pageTitle'));
		$this->render('add');
	}
	
	function admin_index($listingId = null) 
	{
		//$redirectUrl = array("plugin"=>"backend","controller"=>"backend","action"=>"index");
		//$this->__checkDealsFunctionality($redirectUrl);
		$this->pageTitle = __("Deals");
		$conditions = array();
		if($listingId)
		{
			$conditions[] = array("Deal.listing_id" => $listingId);
		}
		if(!isset($this->paginate['conditions']))
		{
			$this->paginate['conditions'] = $conditions;
		}
		$this->paginate['conditions'] = am($this->paginate['conditions'], $conditions);
		$this->Deal->recursive = 0;
		$deals = $this->paginate();
		$this->set('deals', $deals);
		$discountTypes = $this->Deal->getDiscountTypes();
		$this->set('discountTypes',$discountTypes);
		
		$this->set('listingId', $listingId);
	}

	function admin_edit($id) 
	{
		$redirectUrl = array("plugin"=>"backend","controller"=>"backend","action"=>"index");
		$this->Deal->recursive = 0;
		$deal = $this->Deal->findById($id);
		if (!$id || empty($deal)) 
		{
			$this->errorMsg(__('Invalid URL', true));
			$this->redirect($redirectUrl);
		}
		//$this->__checkDealsFunctionality($redirectUrl);
		$pageTitle = __("Edit Deal");
		$this->pageTitle = $pageTitle;
		if (!empty($this->data)) 
		{
			$this->data['Deal']['id'] = $id;
			$defaultAssetId = null;
			if(isset($this->data['DealAsset']['is_default']))
			{
				$defaultAssetId = $this->data['DealAsset']['is_default'];
				unset($this->data['DealAsset']);
			}
			$this->Deal->id = $id;
			if($this->Deal->saveAll($this->data)) //$this->_save($this->data, $id)
			{
				if($defaultAssetId)
				{
					$this->Deal->DealAsset->makeAsDefault($id,$defaultAssetId);
				}
				$this->SuccessMsg(__('The deal has been saved'));
				$this->redirect(array("plugin"=>"deals","controller"=>"deals",'action'=>'index'));
			} else {
				$this->errorMsg(__('The deal could not be saved. Please, try again.'));
			}
		}
		if (empty($this->data)) 
		{
			$this->data = $deal;
		}
		$this->set('pageTitle',$pageTitle);

		$dealAssets = $this->Deal->DealAsset->find('all',array("conditions"=>array('deal_id'=>$id),'recursive'=>-1));
		$this->set("dealAssets",$dealAssets);
		$this->set("deal",$deal);
		$this->Deal->setDealCategoryOptions();
		
		$this->set("showImageTab",true);
		$this->helpers[] = "Assets.Asset";
		$this->helpers[] = "Tabs";
		$this->render("edit");
	}

	function admin_changeStatus($id)
	{
		$deal = $this->Deal->find('first',array('conditions'=>array('id'=>$id),'recursive'=>-1));
		if(empty($deal))
		{
			$this->errorMsg(__('Invalid URL!'));
			$this->redirect($this->referer());
		}
		//$this->__checkDealsFunctionality($this->referer());
		$dealStatus = $deal['Deal']['status'];
		if($dealStatus == Deal::PUBLISH)
		{
			$statusToSave = Deal::UNPUBLISH;
			$successMessage =  __('Deal has been unpublished.');
			$errorMessage =  __('Deal could not be unpublished.');
		} else {
			if(AppUtility::allowPaidListing())
			{
				if(!$this->Deal->isDealEnabledInPaidListing(false, $id))
				{
					$this->errorMsg(__("Deal status cannot be updated due to listing's plan restriction."));
					$this->redirect($this->referer());
					return;
				} else if($this->Deal->isActiveDealsLimitReached(false, $id)) {
					$this->errorMsg(__("Active deal limit exhausted"));
					$this->redirect($this->referer());
					return;
				}
			}
			$statusToSave = Deal::PUBLISH;
			$successMessage =  __('Deal has been published.',true);
			$errorMessage = __('Deal could not be published.',true);
		}
		$result = false;
		if($statusToSave == Deal::PUBLISH)
		{
			$result = $this->Deal->activateDeal($id);
		} else {
			$result = $this->Deal->deactivateDeal($id);
		}
		if($result)
		{
			$this->successMsg($successMessage);
		} else {
			$this->errorMsg($errorMessage);
		}
		$this->redirect($this->referer());
	}

	/*
	 * commented as this is for promotion only
	 * 
	 * 
	function admin_changePurchaseLinkStatus($id)
	{
		$deal = $this->Deal->find('first',array('conditions'=>array('id'=>$id),'recursive'=>-1));
		if(empty($deal))
		{
			$this->errorMsg(__('Invalid URL!'));
			$this->redirect($this->referer());
		}
		$dealType = $deal['Deal']['deal_type'];
		$this->__checkDealsFunctionality($dealType, $this->referer());
		$dealStatus = $deal['Deal']['purchase_link_status'];
		if($dealStatus == Deal::PURCHASE_LINK_ON)
		{
			$statusToSave = Deal::PURCHASE_LINK_OFF;
			$successMessage =  __('Purchase online facility has been deactivated');
			$errorMessage =  __('Purchase online facility could not be deactivated');
		} else {
			$statusToSave = Deal::PURCHASE_LINK_ON;
			$successMessage =  __('Purchase online facility has been activated');
			$errorMessage = __('Purchase online facility could not be activated');
		}
		$this->Deal->id = $id;
		if($this->Deal->saveField('purchase_link_status',$statusToSave))
		{
			$this->successMsg($successMessage);
		} else {
			$this->errorMsg($errorMessage);
		}
		$this->redirect($this->referer());
	}
	*/

	
	function admin_view($id = null) 
	{
		$deal = $this->Deal->find('first',array('conditions'=>array('Deal.id'=>$id),'recursive'=>0));
		if (!$id || empty($deal)) 
		{
			$this->errorMsg(__('Invalid URL.', true));
			$this->redirect(array("plugin"=>"backend","controller"=>"backend",'action'=>'index'));
		}
		//$this->__checkDealsFunctionality();
		$this->pageTitle = $deal['Deal']['title'];
		$discountTypes = $this->Deal->getDiscountTypes();
		$this->set(compact('deal', 'discountTypes'));
		
		$dealAsset = $this->Deal->DealAsset->find('first',array("conditions"=>array('DealAsset.deal_id'=>$id, "DealAsset.is_default"=>1),'recursive'=>-1));
		$this->set("dealAsset",$dealAsset);
	}
	

	function index($categoryId = null) 
	{
		$conditions = array('Deal.status'=>Deal::PUBLISH);
		//$this->__checkDealsFunctionality($this->referer());
		if(!isset($this->params['requested']) || $this->params['requested'] != true)
		{
			$this->actionId = 'dealIndex';
		}
		if($categoryId)
		{
			$conditions[] = array('Deal.list_category_id'=>$categoryId);
		}
		/*
		$cityFilter = null;
		if(isset($this->params['named']['city']) && $this->params['named']['city'])
		{
			$cityFilter = $this->params['named']['city'];
		}
		if($cityFilter)
		{
			$locationString = mysql_real_escape_string($cityFilter);
			$conditions[] = "(MATCH(Listing.location_search_cache) AGAINST (\"$locationString\" IN BOOLEAN MODE))";
		}
		*/
		$conditions[] = "DATE_ADD( Deal.expires, INTERVAL 1 DAY ) > NOW( )";
	
		if(!isset($this->paginate['conditions']))
		{
			$this->paginate['conditions'] = array();
		}
		
		//$cities = $this->Deal->getCitiesForNewsletter();
		//$filterUrls = array('/deals/deals/index/'.$dealType=>'All');
		/*
		foreach ($cities as $city)
		{
			$filterUrls['/deals/index/'.$dealType.'/city:'.$city]=$city;
		}
		*/
		//$this->set('filterUrls', $filterUrls);
		$conditions[] = array('Listing.status = 1');
		$this->paginate['conditions'] = am($this->paginate['conditions'],$conditions);
		
		$this->Deal->recursive = 0;
		$deals = $this->paginate();
		$categories = $this->Deal->ListCategory->find('list',array('conditions'=>array('ListCategory.parent_id'=>null),'order'=>array('ListCategory.name'=>"ASC"),'recursive'=>-1));
		
		$pageTitle = __("Deals");
		$this->pageTitle = $pageTitle;
		
		$this->set('deals', $deals);
		$this->set('pageTitle',$pageTitle);
		$this->set('categoryId',$categoryId);
		$this->set('categories',$categories);

		$discountTypes = $this->Deal->getDiscountTypes();
		$this->set('discountTypes',$discountTypes);
		
		$this->set("hideSideBars", true);
		$this->set('hideLayoutTitle',true);
	}

	function view($id = null) 
	{
		if($id == "undefined")
		{
			exit;
		}
		$deal = $this->Deal->findById($id);
		if (!$id || empty($deal)) 
		{
			$this->errorMsg(__('Invalid URL.', true));
			$this->redirect("/");
		}
		if($deal['Deal']['status'] == Deal::UNPUBLISH)
		{
			$this->errorMsg(__('The deal you are looking for, has been unpublished.', true));
			$this->redirect("/");
		}
		//$this->__checkDealsFunctionality($deal['Deal']['deal_type']);
		if(!isset($this->params['requested']) || $this->params['requested'] != true)
		{
			$this->actionId = 'dealView';
		}
		$differenceInSeconds = (strtotime($deal['Deal']['expires'])+(24*60*60)-1) - time();
		$showBuyButton = 1;
		if($differenceInSeconds < 1 || (($deal['Deal']['total_quantity']!=0) && ($deal['Deal']['total_quantity']<=$deal['Deal']['quantity_consumed']))) // || $deal['Deal']['purchase_link_status']==Deal::PURCHASE_LINK_OFF
		{
			$showBuyButton = 0;
		}
		
		$discount = $deal['Deal']['discount']; //considering discount is entered in perc
		$saving = $discount; //considering discount is entered as flat amt
		
		if($deal['Deal']['discount_type']==0) //if it is flat
		{//get discount perc
			$discount = $deal['Deal']['discount'] / $deal['Deal']['regular_price']*100;
		}
		else
		{//get savings amount
			$saving = $deal['Deal']['regular_price'] - $deal['Deal']['finalPrice'];
		}
		$this->pageTitle = $deal['Deal']['title'];
		$this->set('showBuyButton',$showBuyButton);
		$this->set('discount',number_format($discount,2,'.',''));
		$this->set('saving',number_format($saving,2,'.',''));
		$this->set('differenceInMilliSeconds',$differenceInSeconds*1000);
		$this->set('deal', $deal);
		
		$categories = $this->Deal->ListCategory->find('list',array('conditions'=>array('ListCategory.parent_id'=>null),'order'=>array('ListCategory.name'=>"ASC"),'recursive'=>-1));
		$this->set('categories',$categories);
		
		$this->set("dealViewPage",true);
		$this->set('hideLayoutTitle',true);
		$this->set("hideSideBars", true);
	}

	function newsletter($city = 0)
	{
		Configure::write('debug',0);
		$deals = $this->Deal->getDealsForNewsletter($city);
		$this->layout = 'ajax';
		$this->set('deals',$deals);
	}
	
	function add($listingId)
	{
		//$this->__checkDealsFunctionality();
		$listing = $this->Deal->Listing->find("first",array("conditions"=>array("Listing.id"=>$listingId),"recursive"=>-1));
		if(!$listingId || empty($listing))
		{
			$this->errorMsg(__('Invalid Listing', true));
			$this->redirect("/");
		}
		$authedUserId = $this->Session->read('Auth.User.id');
		if(!$this->Deal->Listing->isOwner($listingId,$authedUserId))
		{
			$this->errorMsg(__('Only listing owner can add deals', true));
			$this->redirect($listing['Listing']['viewUrl']);
		}
		//paid listings check
		if(AppUtility::allowPaidListing())
		{
			if(!$this->Deal->isDealEnabledInPaidListing($listingId))
			{
				$this->errorMsg(__("Deal cannot be added due to listing's plan restriction."));
				$this->redirect("/");
				return;
			} else if($this->Deal->isActiveDealsLimitReached($listingId)) {
				$this->errorMsg(__("Active deal limit exhausted"));
				$this->redirect($listing['Listing']['viewUrl']);
				return;
			}
		}
		if (!empty($this->data))
		{
			$this->data['Deal']['listing_id'] = $listingId;
			$this->data['Deal']['user_id'] = $authedUserId;
			$this->data['Deal']['status'] = Deal::UNPUBLISH;
			$this->Deal->create();
			if($this->Deal->saveAll($this->data)) //$this->_save($this->data)
			{
				$this->SuccessMsg(__('The deal has been saved', true));
				$this->redirect($listing['Listing']['viewUrl']);
			} else {
				$this->errorMsg(__('The deal could not be saved. Please try again.', true));
			}
		}
		
		$pageTitle = sprintf(__("Add new deal for listing : %s"),$listing['Listing']['title']);
		$this->pageTitle = $pageTitle;
		
		$this->Deal->setDealCategoryOptions();
		$this->set(compact('listing', 'pageTitle'));
	}
	
	function edit($id)
	{
		$authedUserId = $this->Session->read('Auth.User.id');
		$redirectUrl = "/";
		$deal = $this->Deal->find('first',array('conditions'=>array('Deal.id'=>$id, 'Deal.user_id'=>$authedUserId),'recursive' => 0));
		if (!$id || empty($deal)) 
		{
			$this->errorMsg(__('Invalid URL', true));
			$this->redirect($redirectUrl);
			return;
		}
		//$this->__checkDealsFunctionality($redirectUrl);
		if (!empty($this->data))
		{
			$this->data['Deal']['id'] = $id;
			$defaultAssetId = null;
			if(isset($this->data['DealAsset']['is_default']))
			{
				$defaultAssetId = $this->data['DealAsset']['is_default'];
				unset($this->data['DealAsset']);
			}
			$this->Deal->id = $id;
			if($this->Deal->saveAll($this->data)) //$this->_save($this->data, $id)
			{
				if($defaultAssetId)
				{
					$this->Deal->DealAsset->makeAsDefault($id,$defaultAssetId);
				}
				$this->SuccessMsg(__('The deal has been saved'));
				$this->redirect(array("plugin"=>"deals","controller"=>"deals",'action'=>'myDeals'));
			} else {
				$this->errorMsg(__('The deal could not be saved. Please, try again.'));
			}
		}
		if (empty($this->data)) 
		{
			$this->data = $deal;
		}
		$pageTitle = __("Edit Deal");
		$this->pageTitle = $pageTitle;
		$this->set('pageTitle',$pageTitle);
	
		$dealAssets = $this->Deal->DealAsset->find('all',array("conditions"=>array('deal_id'=>$id),'recursive'=>-1));
		$this->set("dealAssets",$dealAssets);
		$this->set("deal",$deal);
	
		$this->Deal->setDealCategoryOptions();
	
		$this->set("showImageTab",true);
		$this->helpers[] = "Assets.Asset";
		$this->helpers[] = "Tabs";
	}
	
	function myDeals()
	{
		$authedUserId = $this->Session->read('Auth.User.id');
		$this->pageTitle = __("My posted deals");
		
		if(!$this->Deal->isDealEnabled())
		{
			$this->errorMsg(__('Invalid URL', true));
			$this->redirect($this->referer());
			return;
		}
		
		//showing all deals either published or unpublished
		$conditions = array("Deal.user_id" => $authedUserId);
		if(!isset($this->paginate['conditions']))
		{
			$this->paginate['conditions'] = array();
		}
		$this->paginate['conditions'] = am($this->paginate['conditions'],$conditions);
		$this->paginate['recursive'] = 0;
		$deals = $this->paginate();
		
		$this->set('deals', $deals);
		//$categories = $this->Deal->ListCategory->find('list',array('conditions'=>array('ListCategory.parent_id'=>null),'order'=>array('ListCategory.name'=>"ASC"),'recursive'=>-1));
		//$this->set('categories',$categories);
		//$discountTypes = $this->Deal->getDiscountTypes();
		//$this->set('discountTypes',$discountTypes);
	}
	
	function delete($dealId)
	{
		$authedUserId = $this->Session->read('Auth.User.id');
		$deal = $this->Deal->find('first',array('conditions'=>array('Deal.id'=>$dealId, 'Deal.user_id'=>$authedUserId),'recursive'=>-1));
		if(!$dealId || !$deal || empty($deal))
		{
			$this->errorMsg(__('Invalid URL', true));
			$this->redirect($this->referer());
			return;
		}
		if(!$this->Deal->Listing->isOwner($listingId,$authedUserId))
		{
			$this->errorMsg(__('Only listing owner can add deals', true));
			$this->redirect($listing['Listing']['viewUrl']);
		}
		
		//$this->__checkDealsFunctionality($this->referer());
		if($this->Deal->del($dealId))
		{
			$this->successMsg(__('Deal deleted successfully', true));
		} else {
			$this->errorMsg(__('Deal could not be deleted. Please try again.', true));
		}
		$this->redirect($this->referer());
	}
	
	function admin_delete($dealId)
	{
		$deal = $this->Deal->find('first',array('conditions'=>array('Deal.id'=>$dealId),'recursive'=>-1));
		if(!$dealId || !$deal || empty($deal))
		{
			$this->errorMsg(__('Invalid URL', true));
			$this->redirect($this->referer());
			return;
		}
		//$this->__checkDealsFunctionality($this->referer());
		if($this->Deal->del($dealId))
		{
			$this->successMsg(__('Deal deleted successfully', true));
		} else {
			$this->errorMsg(__('Deal could not be deleted. Please try again.', true));
		}
		$this->redirect($this->referer());
	}
	
	
	function __checkDealsFunctionality($redirectUrl = false)
	{
		if($redirectUrl === false)
		{
			if(isset($this->params['admin']) && $this->params['admin'])
			{
				$redirectUrl = array("plugin"=>"backend","controller"=>"backend","action"=>"index");
			} else {
				$redirectUrl = "/";
			}
		}
		if(!$this->Deal->isDealEnabled())
		{
			$this->errorMsg(__('Deals functionality is not enabled', true));
			$this->redirect($redirectUrl);
		}
	}
	
	/*
	private function _save($data, $id=null)
	{
		if(isset($data["Deal"]["asset_inputs"]) && !empty($data["Deal"]["asset_inputs"]))
		{
			foreach($data["Deal"]["asset_inputs"] as $key=>$assetData)
			{
				if(!isset($assetData["name"]["name"]) || !$assetData["name"]["name"])
				{
					unset($data["Deal"]["asset_inputs"][$key]);
				}
			}
		}
		if(!empty($data["Deal"]["asset_inputs"]))
		{
			$data["DealAsset"] = $data["Deal"]["asset_inputs"];
		}
		unset($data["Deal"]["asset_inputs"]);
		$this->log($data,'cccc');
		$this->Deal->create();
		$this->Deal->id = $id;
		return $this->Deal->saveAll($data);
	} 
	*/
	
}
?>